package binarytree;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/18 15:21
 * https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
 * 给定一个二叉树的根节点 root ，返回它的 中序 遍历。  左 根 右
 */
public class InorderTraversal {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }

    }

    public static List<Integer> result;

    /**
     * 中序遍历递归方法
     * @param root
     * @return
     */
    public static List<Integer> inorderTraversal(TreeNode root) {
        result = new ArrayList<>();
        inorder(root);
        return result;
    }

    public static void inorder(TreeNode root) {
        if (root != null) {
            inorder(root.left);
            result.add(root.val);
            inorder(root.right);
        }
    }

    /**
     * 中序遍历非递归方法
     * @param root
     * @return
     */
    private static List<Integer> inorderTraversal1(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        //同时为空跳出循环
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                //左孩子为空时跳出循环
                root = root.left;
            }
            //弹出根节点
            root = stack.pop();
            result.add(root.val);
            root = root.right;
        }
        return result;
    }

    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(1);
        TreeNode right = new TreeNode(2);
        right.left = new TreeNode(3);
        treeNode.right=right;
        List<TreeNode> treeNodes = Arrays.asList(treeNode);
        List<Integer> integers = inorderTraversal1(treeNode);
        System.out.println();
    }


}
